import React from 'react'
import {inject, observer} from 'mobx-react';
import {toJS} from 'mobx';
import {ActivityIndicator,Tools,List,WhiteSpace,Button,Modal,Bubble,Toast } from 'weaver-mobile';
import {Route, withRouter } from 'react-router-dom';
import { RouteLayout,Form } from 'weaver-mobile-page';
import InvoiceInfo from './InvoiceInfo';
import AutoCheck from './AutoCheck';
import QueueAnim from 'rc-queue-anim';
import {getUrlParam} from '../../util/common';
const getLabel = Tools.getLabel;
const operation = Modal.operation;



@withRouter
@inject ('receptionStore')
@observer
class Ocr extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            fplx:0,
            sreenHeight:0,
        };
        

        const {location:{search}} = this.props;
        this.routeInfo = getUrlParam(search);

    }

    static defaultProps = {
        prefixCls:"fna-reception-type"
    }

    componentDidMount() {
        const {receptionStore} = this.props;
        const {getHandSetPage,getEquipmentFn} = receptionStore;

        let params = {
            type:this.routeInfo.type,
            result:this.routeInfo.result,
        }
        getEquipmentFn();
        this.setState({
            sreenHeight:document.documentElement.clientHeight-47
        })

        if(this.routeInfo.type == 'Ocr'){
          
        }else if(this.routeInfo.type == 'EnterByHand'){ //手动识别
            getHandSetPage(params,(value)=>{
                this.setState({
                    fplx:value
                })
            })
        }
    }

    componentWillUnmount(){
        const {receptionStore} = this.props;
        const {setInvoiceInfo} = receptionStore;
        setInvoiceInfo();
    }


    render() {
        const { receptionStore,prefixCls } = this.props;
        const { ocrInfo,ocrRoute,loading_page,autoCheckRoute,formEnterByHand,invoiceResult,checkJson } = receptionStore;
        const { formParams} = formEnterByHand;

        return (
            <div className={`${prefixCls}`}>
                <ActivityIndicator
                    toast
                    text="Loading..."
                    animating={loading_page}
                />
                {this.getpage(this.routeInfo.type)}
            

                {/* 路由层 */}
                <div>
                    <Route
                        key={ocrRoute.id}
                        path={ocrRoute.path}
                        render={() => {
                            return (
                                <RouteLayout getContainer={() => document.getElementById("root")}>
                                    <div
                                        key="crmListLayout"
                                        className="wm-route-layout"
                                    >
                                        
                                        <InvoiceInfo 
                                            ocrInfo={ocrInfo} 
                                            callBackFn={(value)=>{this.callBackFn(value)}}
                                            callBackUpdata={(value)=>{this.callBackUpdata(value)}}
                                        />
                                    </div>
                                </RouteLayout>
                            )
                        }}
                    /> 
                </div>
                <div>
                    <Route
                        key={autoCheckRoute.id}
                        path={autoCheckRoute.path}
                        render={() => {
                            return (
                                <RouteLayout getContainer={() => document.getElementById("root")}>
                                    <div
                                        key="crmListLayout"
                                        className="wm-route-layout"
                                    >
                                        
                                        <AutoCheck isForm={this.routeInfo.isForm} invoiceResult={invoiceResult} checkJson={checkJson}/>
                                    </div>
                                </RouteLayout>
                            )
                        }}
                    /> 
                </div>
                
            </div>
        )
    }

    getpage = (type) =>{
        const {receptionStore} = this.props;
        const {formEnterByHand,invoiceInfo} = receptionStore;
        
        let comment = '';
        if(type == 'Ocr'){
            comment = [
                <div id="container1" key={'container1'}>
                    {invoiceInfo.length > 0 && <div className="title" style={{textAlign:'center',padding:'10px 8px'}}>{getLabel(517369,'请选择发票')}</div>}
                    {invoiceInfo.length > 0 ? <div className="invoice-content" style={{height:this.state.sreenHeight-81,overflow:'auto','WebkitOverflowScrolling': 'touch',paddingBottom:'45px'}}>
                        {invoiceInfo.map(items =>{
                            let stateValue = '';
                            if(items.state == '0'){
                                stateValue = '识别失败';
                            }else if(items.state == '1'){
                                stateValue = '识别成功';
                            }else if(items.state == '2'){
                                stateValue = '验票失败';
                            }else if(items.state == '3'){
                                stateValue = '验票成功';
                            }
                            
                            return (
                                <div key={items.invoiceId} onClick={()=>{items.state == '0' ? '' : this.viewInvoice(items.invoiceId,items.newImage)}} className={`fna-ocr-invoiceCSS`}>
                                    <div className={`fna-ocr-invoiceCSS-left`}><img src={items.newImage}/></div>
                                    <div className={`fna-ocr-invoiceCSS-middle`}>
                                        <div>{items.invoiceNumber}</div>
                                        <div>{items.billingDate}</div>
                                        <div>{items.description}</div>
                                    </div>
                                    <div className={`fna-ocr-invoiceCSS-right`}>
                                        <div>{items.taxIncludedPrice}</div>
                                        <div className={`state_${items.state}`}>{stateValue}</div>
                                    </div>
                                </div>
                            )

                        })}
                    </div>:<div className="invoice-noContent" style={{height:this.state.sreenHeight}}></div>}
                    

                    <div className="invoice-footer">
                        <Button type="primary" onClick={() => operation(this.getButton())} >{getLabel(514561,'选择发票')}</Button>
                    </div>
                    
                </div>
            ]
            
           
        }else if(type == 'EnterByHand'){
            comment = [
                <div className={'fna-EnterByHand'} key={'EnterByHand'}>
                    <h4>{getLabel(517371,'手动输入验票')}</h4>
                    <Form store={formEnterByHand} onChange={this.onChange}>
                        <List>
                            {this.getFields()}
                        </List>

                        <WhiteSpace />
                        <div className={'btn-box'}>
                            <Button type="gost" onClick={()=>{this.resetForm()}} >{getLabel(509254,'重置')}</Button>
                            <Button type="primary" onClick={()=>{this.autoCheck()}} >{getLabel(509254,'自动查验')}</Button>
                        </div>
                    </Form> 
                </div>
            ]
        }

        return comment;
    }

    //重置form
    resetForm = () =>{
        const { receptionStore } = this.props;
        const { formEnterByHand } = receptionStore;
        const { conditioninfo } = formEnterByHand;
    
        // formEnterByHand.resetConditions(conditioninfo, pathname)
        formEnterByHand.resetFields()
    }

    //获取按钮
    getButton = () =>{
        let btn = [
            { text: ' ',
                style:{background:"no-repeat url('/images/fna/fnaMobile/pz.png') left",backgroundSize:'40px 40px',backgroundPosition: '10px'}, 
                onPress: () => {this.takePicture()} },
            { text: ' ',
                style:{background:"no-repeat url('/images/fna/fnaMobile/zptk.png') left",backgroundSize:'80px 40px',backgroundPosition: '10px'}, 
                onPress: () => {this.photoAlbum()}},
            { text: ' ',
                style:{background:"no-repeat url('/images/fna/fnaMobile/qx.png') left",backgroundSize:'40px 40px',backgroundPosition: '10px'}, 
                onPress: () => {}},
        ];

        return btn;
        
    }

    getFields = () => {
        const { receptionStore } = this.props;
        const { formEnterByHand } = receptionStore;

        const { conditioninfo, isInit,formParams } = formEnterByHand;

        const groups = [];
        if (isInit) {
            conditioninfo.forEach((group) => {
                const fields = [];
                group.items.forEach((field) => {

                    if(field.domkey[0] === "checkCode"){
                        if(this.state.fplx == 1 || this.state.fplx == 15 || this.state.fplx == 16){
                            fields.push(<Form.Item
                                key={field.domkey.join('__')}
                                form={formEnterByHand}
                                fieldConfig={field}
                                onChange={this.onChange.bind(this)}
                            />) 
                        }
                        
                    }else if(field.domkey[0] === "priceWithoutTax"){
                        if(this.state.fplx == 2 || this.state.fplx == 12){
                            fields.push(<Form.Item
                                key={field.domkey.join('__')}
                                form={formEnterByHand}
                                fieldConfig={field}
                                onChange={this.onChange.bind(this)}
                            />) 
                        }
                    } else{
                        fields.push(<Form.Item
                            key={field.domkey.join('__')}
                            form={formEnterByHand}
                            fieldConfig={field}
                            onChange={this.onChange.bind(this)}
                        />) 
                    }
                    
                });
                
                groups.push(<div key='loading'>{fields}</div>)
            })

            
        }

        return <QueueAnim duration={1000} type={['bottom']}>{groups}</QueueAnim>;
    }    

    onChange = (paramsObj,value) =>{
        const {receptionStore} = this.props;
        const {formEnterByHand} = receptionStore;

        const domkey = paramsObj.domkey[0];
        if(domkey == "invoiceCode"){
            if(value.length == 10 || value.length == 12){
                let invoiceType = 0;
                if(value.length == 10){
                    let eight = value.substring(7,8);
                    if("1" == eight || "2" == eight || "5" == eight || "7" == eight){
                        invoiceType = 1;
                    }else if("3" == eight || "6" == eight){
                        invoiceType = 2;
                    }
                }else if(value.length == 12){
                    let first = value.substring(0,1);
                    let eight = value.substring(7,8);
                    let elevenTwelve = value.substring(10,11) + value.substring(11,12);
                    if("0" == first){
                        if ("11" == elevenTwelve) {//增值税电子普通发票
                            invoiceType = 15;
                        } else if ("06" == elevenTwelve || "07" == elevenTwelve) {//增值税卷票
                            invoiceType = 16;
                        } else if ("04" == elevenTwelve || "05" == elevenTwelve) {//增值税普通发票
                            invoiceType = 2;
                        } else if ("12" == elevenTwelve) {//通行费发票就是增值税电子发票
                            invoiceType = 3;
                            invoiceType = 15;
                        }
                    }
                    if("1" == first && "2" == eight){//机动车销售统一发票
                        invoiceType = 4;
                    }
                    if("0" == first && "17" == elevenTwelve){//二手车销售统一发票
                        invoiceType = 5;
                    }
                }

                if(invoiceType == 1){
                    this.setState({fplx:2})
                }else if(invoiceType == 2){
                    this.setState({fplx:1})
                }else if(invoiceType == 15 || invoiceType == 16){
                    this.setState({fplx:invoiceType})
                }else if(invoiceType == 4){
                    this.setState({fplx:12})
                }else{
                    this.setState({fplx:0})

                }
            }else{
                this.setState({fplx:0})
            }
        }
        formEnterByHand.updateField(domkey,value);
    }


    //查看发票
    viewInvoice = (invoiceId,newImage) =>{
        const {receptionStore,history} = this.props;
        const {ocrRoute,setOcrInfo} = receptionStore;

        setOcrInfo({
            invoiceId:invoiceId,
            newImage:newImage
        })
        history.push(ocrRoute.path);
    }

    //拍照
    takePicture = (e,params) =>{
        const isExist = window.em_ssoInit && window.em && window.em.checkJsApi('chooseImage');
        if (!isExist) {Toast.fail(getLabel(525804,'对不起,暂不支持该应用'));return};

        let that = this;
        window.em_ssoInit().then(() => {

            window.em.chooseImage({
                count: 10, // 最大可选照片数，默认9
                sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
                success: function (res) {
                    let localIds = res.localIds; // 返回选定照片的本地ID列表
                    localIds.forEach(function(localId){
                        window.em.getLocalImgData({
                            localId: localId,
                            success: function(res){
                                let data = res.localData;
                                that.addImg(data);

                            }
                        });
                    });

                }
            });
        }).catch((res) => {
            alert("连续拍照插件异常,使用原始插件");
            // alert(JSON.stringify(res));
            //var dom="<input type='file' accept='image/*' multiple='multiple' name='file_head' id='file_head' style='position:absolute;opacity:0;margin-top: -50px;height: 50px;width: 33%;'>";
            //$("#chooseInvoice").append(dom);
        })
    }

    //base64数据添加data:image/jpeg;base64,前缀
    addImg = (data) =>{
        let base64PicData = "data:image/jpeg;base64,"+data;
        {console.log('base64PicData',base64PicData)}
        this.appendDetail(base64PicData);
    }

    appendDetail = (data) =>{
        const {receptionStore} = this.props;
        const {enterInvoiceByOcr} = receptionStore;

        enterInvoiceByOcr({
            operate:'multiCheck',
            fileData:data
        });

    }



    //选照片
    photoAlbum = (e,params) =>{
        const isExist = window.em_ssoInit && window.em && window.em.checkJsApi('chooseImage');
        if (!isExist) {Toast.fail(getLabel(525804,'对不起,暂不支持该应用'));return};
        
        let that = this;
        window.em_ssoInit().then(() => {
            window.em.chooseImage({
                count: 10, // 最大可选照片数，默认9
                sourceType: ['album'], // 可以指定来源是相册还是相机，默认二者都有
                success: function (res) {
                    var localIds = res.localIds; // 返回选定照片的本地ID列表
                    
                    // let that = this;
                    localIds.forEach(function(localId){
                        window.em.getLocalImgData({
                            localId: localId,
                            success: function(res){
                                var data = res.localData;
                                that.addImg(data);

                            }

                        });
                    });

                }
            });
        }).catch((res) => {
            //alert("连续选照片插件异常,使用原始插件");
            //var dom="<input type='file' accept='image/*' multiple='multiple' name='file_head' id='file_head' style='position:absolute;opacity:0;margin-top: -50px;height: 50px;width: 33%;'>";
            //$("#chooseInvoice").append(dom);
        })
    }

    //回调 函数
    callBackFn = (value) =>{
        const {receptionStore} = this.props;
        const {invoiceInfo,setInvoiceInfo} = receptionStore;
        let _invoiceInfo = [];
        for(let i=0;i<invoiceInfo.length;i++){
            if(invoiceInfo[i].invoiceId == value){
                // _invoiceInfo.splice(i,1);
            }else{
                _invoiceInfo.push(invoiceInfo[i])
            }
        }
        setInvoiceInfo(_invoiceInfo);
    }

    //更新数据
    callBackUpdata = (value) =>{
        const {receptionStore} = this.props;
        const {invoiceInfo,setInvoiceInfo,ocrInfo} = receptionStore;
        // alert(JSON.stringify(value))
        let _invoiceInfo = invoiceInfo;
        for(let i=0;i<_invoiceInfo.length;i++){
            if(_invoiceInfo[i].invoiceId == value.invoiceId){
                _invoiceInfo[i] = value;
                _invoiceInfo[i]['newImage'] = ocrInfo.newImage;
            }
        }
        setInvoiceInfo(_invoiceInfo);
    }

    autoCheck = () =>{
        const {receptionStore} = this.props;
        const {formEnterByHand} = receptionStore;
        const { formParams} = formEnterByHand;

        
        
        if(this.state.fplx == 1 || this.state.fplx == 15 || this.state.fplx == 16){
            formEnterByHand.updateField('priceWithoutTax',1);
            let pass = formEnterByHand.doValidate().pass;
            if(pass){
                this.getInvoiceParams();
            }
        }else if(this.state.fplx == 2 || this.state.fplx == 12){
            formEnterByHand.updateField('checkCode',1);
            let pass = formEnterByHand.doValidate().pass;
            if(pass){
                this.getInvoiceParams();
            }
        }else{
            Bubble.error('失败')
        }

        
        
    }

    //发票参数
    getInvoiceParams = () =>{
        const {receptionStore} = this.props;
        const {getInvoiceInfoByCheck,formEnterByHand,autoCheckRoute} = receptionStore;
        const { formParams} = formEnterByHand;
        let {invoiceNumber,invoiceCode,billingDate,priceWithoutTax,checkCode} = formParams;
        billingDate = billingDate.replace("-","").replace("-","");
        let result = '';

        if(this.state.fplx == 1 || this.state.fplx == 15 || this.state.fplx == 16){
            result = "01,04,"+invoiceCode+","+invoiceNumber+",0.00,"+billingDate+","+checkCode+",0000,";
        }else if(this.state.fplx == 2 || this.state.fplx == 12){
            result = "01,01,"+invoiceCode+","+invoiceNumber+","+priceWithoutTax+","+billingDate+","+"000000,0000,";
        }

        getInvoiceInfoByCheck({result:result},()=>{
            this.props.history.push(autoCheckRoute.path)
        })

        return result
    }

    

}

export default Ocr;